package own.stu.inter.crawler;

import com.google.common.io.Files;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Callable;

@Slf4j
@AllArgsConstructor
@Data
public class ChapterTask implements Callable<String> {

    Crawler crawler;

    static String rootPath = "/Users/qim/Desktop/novel/";

    @Override
    public String call() throws InterruptedException {
        BlockingDeque<String> taskDeque = crawler.getTaskDeque();
        String path;
        while ((path = taskDeque.take()) != null) {
            if (StringUtils.isBlank(path)) {
                continue;
            }
            saveChapter(path);
        }
        return "";
    }

    public String saveChapter(String path) {
        log.info("get chapter {}， title : {}", path);
        String body = null;
        try {
            final String fileName = ContentAnalyze.getContent(path, "https://m.ahfgb.com/25/25741/", ".html");
            final File file = new File(rootPath + fileName);
            if (!file.exists()) {
                Files.touch(file);
            }

            body = crawler.getResponseBody(path);
            StringBuilder sb = new StringBuilder();
            String title = ContentAnalyze.getTitle(body);
            String content = ContentAnalyze.getContent(body);

            log.info("get chapter {}， title : {}", path, title);

            sb.append(title).append(content);

            String nextPageUrl = ContentAnalyze.getNextPageOfChapter(body);
            do {
                String nextPageContent = getNextPageAtCurChapter(nextPageUrl, title);
                if (StringUtils.isBlank(nextPageContent)) {
                    break;
                }

                nextPageUrl = ContentAnalyze.getNextPageOfChapter(nextPageContent);

                content = ContentAnalyze.getContent(nextPageContent);
                sb.append(content);
            } while (true);

            Files.write(sb.toString().getBytes(), file);

            crawler.getMergeService().markLoaded(path);
        } catch (Exception e) {
            log.error("error get content: {}, error: ", path, e);
        }
        return "";
    }

    public String getNextPageAtCurChapter(String nextPageUrl, String title) throws Exception {

        if (StringUtils.isBlank(nextPageUrl)) {
            return "";
        }
        String body = crawler.getResponseBody(nextPageUrl);
        if (StringUtils.isBlank(body)) {
            log.error("error get content: {} on {}", nextPageUrl, title);
            return "";
        }
        return body;
    }
}
